﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Entities;
using ARR.UI.Views;
using ARR.UI.EnvoyImporterService;
using System.Collections.ObjectModel;
using ARR.UI.ArticlesService;
using System.Windows;
using ARR.UI.Commands;
using System.Windows.Input;
using ARR.Shared;
using ARR.UI.Models;
using System.ServiceModel;
using ARR.UI.ExcelImporterService;

namespace ARR.UI.ViewModels
{
    public class UnifiedImporterViewModel : WorkspaceViewModel
    {
        public IUnifiedImporterModel model;
        private ICommand cancelCommand;
        private ICommand nextCommand;
        private ICommand retryCommand;
        private ICommand startCommand;

        public UnifiedImporterViewModel(IUnifiedImporterModel model)
        {
            base.DisplayName = Labels.ImportadorUnificado;
            this.model = model;

            CurrentStep = 0;
            HasPassedCurrentStep = null;
        }

        public ICommand NextCommand
        {
            get
            {
                if (nextCommand == null)
                {
                    nextCommand = new RelayCommand(param => NextStep(), p => (HasPassedCurrentStep.HasValue && HasPassedCurrentStep.Value && CurrentStep < 2));
                }
                return nextCommand;
            }
        }

        public ICommand RetryCommand
        {
            get
            {
                if (retryCommand == null)
                {
                    retryCommand = new RelayCommand(param => RetryCurrentStep(), p => (HasPassedCurrentStep.HasValue && !HasPassedCurrentStep.Value));
                }
                return retryCommand;
            }
        }

        public ICommand StartCommand
        {
            get
            {
                if (startCommand == null)
                {
                    startCommand = new RelayCommand(param => NextStep(), p => CurrentStep == 0);

                }
                return startCommand;
            }
        }
        
        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => Cancel());
                }
                return cancelCommand;
            }
        }


        public ObservableCollection<ImporterResult> Results
        {
            get
            {
                return new ObservableCollection<ImporterResult>(model.Results.OrderBy(x => x.Description));
            }
        }
        
        public Visibility IsVisibleResultsGV
        {
            get
            {
                if (Results != null && Results.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        
        public string Step1ImagePath { get; set; }

        public string Step2ImagePath { get; set; }

        public int CurrentStep { get; set; }

        public bool? HasPassedCurrentStep { get; set; }

        public bool IsBusy { get; set; }

        
        private void Cancel()
        {

        }

        private void NextStep()
        {
            switch (CurrentStep)
            {
                case 0:
                    RunStep1();
                    break;
                case 1:
                    RunStep2();
                    break;                
            }

            OnPropertyChanged<UnifiedImporterViewModel>(p => p.Results);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsVisibleResultsGV);

            if (CurrentStep < 2)
                CurrentStep += 1;
        }

        private void RetryCurrentStep()
        {
            CurrentStep -= 1;
            NextStep();
        }


        private void RunStep1()
        {
            switch (WorkspaceData.Instance.Country.SalesImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;

                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.UnifiedImporterStep1Completed += new EventHandler<UnifiedImporterStep1CompletedEventArgs>(excelService_UnifiedImporterStep1Completed);
                            excelService.UnifiedImporterStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;

                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.UnifiedImportStep1Completed += new EventHandler<EnvoyImporterService.UnifiedImportStep1CompletedEventArgs>(envoyService_UnifiedImportStep1AsyncCompleted);
                            envoyService.UnifiedImportStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }

            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsBusy);      

            
        }

        private void RunStep2()
        {
            switch (WorkspaceData.Instance.Country.SalesImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;

                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.UnifiedImporterStep2Completed += new EventHandler<UnifiedImporterStep2CompletedEventArgs>(excelService_UnifiedImporterStep2Completed);
                            excelService.UnifiedImporterStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;

                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.UnifiedImportStep2Completed += new EventHandler<EnvoyImporterService.UnifiedImportStep2CompletedEventArgs>(envoyService_UnifiedImportStep2AsyncCompleted);
                            envoyService.UnifiedImportStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }

            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsBusy);      

        }


        void excelService_UnifiedImporterStep1Completed(object sender, UnifiedImporterStep1CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep1Callback(e.Result);

            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }
        }

        void excelService_UnifiedImporterStep2Completed(object sender, UnifiedImporterStep2CompletedEventArgs e)
        {            
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep2Callback(e.Result);

            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }
        }


        void envoyService_UnifiedImportStep1AsyncCompleted(object sender, UnifiedImportStep1CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep1Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }
        }

        void envoyService_UnifiedImportStep2AsyncCompleted(object sender, UnifiedImportStep2CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep2Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }
        }


        private void RunStep1Callback(List<ImporterResult> results)
        {
            model.Results = results;

            Step1ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step1ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }
            }

            IsBusy = false;
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.Step1ImagePath);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.Results);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsVisibleResultsGV);
        }

        private void RunStep2Callback(List<ImporterResult> results)
        {
            model.Results = results;

            Step2ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step2ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }
            }

            IsBusy = false;
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.Step2ImagePath);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.Results);
            OnPropertyChanged<UnifiedImporterViewModel>(p => p.IsVisibleResultsGV);
        }

    }
}
